package com.hmdp.utils;
import org.apache.tomcat.jni.Time;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.Currency;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock{

    private String name;
    private StringRedisTemplate stringRedisTemplate;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private static final String KEY_PREFIX = "lock:";
    private static final String UUID_PREFIX = UUID.randomUUID().toString();
    private static final DefaultRedisScript<Long> LUA_SCRRPT;

    static {
        LUA_SCRRPT = new DefaultRedisScript<>();
        LUA_SCRRPT.setLocation(new ClassPathResource("unLock.lua"));
        LUA_SCRRPT.setResultType(Long.class);
    }


    /**
     * 尝试获取锁
     * @param timeoutSec
     * @return
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        // 获取线程id
        String threadId =UUID_PREFIX + Thread.currentThread().getId();
        // 获取锁
        boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name,threadId ,timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
        stringRedisTemplate.execute(
                LUA_SCRRPT,
                Collections.singletonList(KEY_PREFIX + name),
                UUID_PREFIX + Thread.currentThread().getId()
        );
    }

    // 释放锁
    /*@Override
    public void unLock() {
        // 标识
        String threadId =UUID_PREFIX + Thread.currentThread().getId();
        // 获取存储的标识
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        // 判断是否相等
        if(!id.equals(threadId)){
            return;
        }
        stringRedisTemplate.delete(KEY_PREFIX + name);
    }*/
}
